/**
 * Copyright (C), 2020, Y2 T205
 * FileName: SeckillServiceImpl
 * Author: Lenovo
 * Date: 2020-05-31 10:26
 * Description:
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */


package com.atguigu.gulimall.seckill.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SeckillSkuVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.w3c.dom.ranges.Range;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author Lenovo
 * @create 2020-05-31
 * @since 1.0.0
 */
@Service
public class SeckillServiceImpl implements SeckillService {
@Autowired
   CouponFeignService couponFeignService;

@Autowired
    StringRedisTemplate redisTemplate;

@Autowired
    ProductFeignService productFeignService;

@Autowired  //分布式信号量
    RedissonClient redissonClient;

@Autowired
    RabbitTemplate rabbitTemplate;

//活动要用的前缀
    private final String SESSIONS_CACHE_PREFIX="seckill:sessions:";
//    商品活动秒杀的前缀
    private final String SKUKILL_CACHE_PREFIX="seckill:skus:";

    private final String SKU_STOCK_SEMAPHORE="seckill:stock:";//+商品的随机码


    @Override
    public void uploadSeckillSkuLatest3Days() {
//        1.扫描最近三天需要参与秒杀的活动
        R session = couponFeignService.getLases3DaySession();
        if(session.getCode()==0){
//            上架商品
            List<SeckillSessionsWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });

//            缓存到redis
//            1.缓存活动的信息
            saveSessionInfos(sessionData);
//            2.缓存关联商品的信息
            saveSessionSkuInfos(sessionData);

        }




    }


//    返回当前时间可以参与的秒杀商品的信息
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
//      1、确定当前时间属于哪个秒杀场次
        long time =new Date().getTime();

        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for(String key:keys){
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
           Long start= Long.parseLong(s[0]);
           Long end =Long.parseLong(s[1]);


           if(time>=start && time<=end){
//               2.获取这个秒杀场次的所需要的的所有商品额信息
               List<String> range = redisTemplate.opsForList().range(key, -100, 100);
               BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
               List<String> list = hashOps.multiGet(range);
               if(list!=null){
                   List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                       SeckillSkuRedisTo redis = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
//                       redis.setRandomCode(null);  //当前秒杀开始就需要随机码
                       return redis;
                   }).collect(Collectors.toList());
                   return collect;
               }
               break;
           }
        }


//        2.获取这个秒杀场次需要的所有商品信息

        return null;
    }

    /*获取某个商品的秒杀预告信息*/
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys =hashOps.keys();
        if(keys !=null && keys.size()>0){
            String regx="\\d_"+skuId;  //别管是第几场的skuid只要带有需要的skuid，就可以
            for(String key:keys){
                if(Pattern.matches(regx,key)){
                    if(Pattern.matches(regx,key)){
                        String json =hashOps.get(key);
                        SeckillSkuRedisTo skuRedisTo=JSON.parseObject(json,SeckillSkuRedisTo.class);

//随机码
                        long current =new Date().getTime();
                        if(current>=skuRedisTo.getStartTime()&&current<=skuRedisTo.getEndTime()){

                        }else{
                            skuRedisTo.setRandomCode(null);
                        }
                        return skuRedisTo;
                    }
                }
            }
        }

        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {

        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();

//        1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String json = hashOps.get(killId);
        if(StringUtils.isEmpty(json)){
            return null;
        }else{
            SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);

//            校验合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long time =new Date().getTime();

           long ttl=endTime-time;
//1.校验时间的合法性
            if(time>=startTime&&time<=endTime){
//                2.校验随机码和商品id
                String randomCode = redis.getRandomCode();
                String skuId=redis.getPromotionSessionId()+"_"+redis.getSkuId();
                if(randomCode.equals(key)&&killId.equals(skuId)){
//                    3.验证数量是否合理
                    if(num<=redis.getSeckillLimit()){
//                      幂等性问题  4。验证是否购买过  如果只要秒杀成功，就去站位 userid_sessionId_skuId
                        String redisKey =respVo.getId()+"_"+skuId;
//                        自动过期
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if(aBoolean){
//                            站位成功说明没买过，可以买
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);

                                boolean b = semaphore.tryAcquire(num);

                                if(b){
                                    //                                秒杀成功
//                                快速下单  发送mq消息
                                    String timeId = IdWorker.getTimeId();

                                    SeckillOrderTo orderTo =new SeckillOrderTo();

                                    orderTo.setOrderSn(timeId);
                                    orderTo.setMemberId(respVo.getId());
                                    orderTo.setNum(num);
                                    orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                    orderTo.setSkuId(redis.getSkuId());
                                    orderTo.setSeckillPrice(redis.getSeckillPrice());


                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);



                                    return timeId;
                                }
                                return null;




                        }else{
                            return null;
                        }
                    }
                }else{
                    return  null;
                }

            }else{
                return null;
            }
        }
        return null;
    }

    //            1.缓存活动的信息
    private void saveSessionInfos( List<SeckillSessionsWithSkus> sessions){
        sessions.stream().forEach(session->{
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key =SESSIONS_CACHE_PREFIX+startTime+"_"+endTime;
            Boolean haskey =redisTemplate.hasKey(key);
//            缓存活动的信息
            if(!haskey){
                List<String> collect = session.getRelationSkus().stream().map(item->item.getPromotionSessionId()+"_"+item.getSkuId().toString()).collect(Collectors.toList());

                redisTemplate.opsForList().leftPushAll(key,collect);
            }
        });
    }
    //            2.缓存关联商品的信息
    private void saveSessionSkuInfos( List<SeckillSessionsWithSkus> sessions){
        sessions.stream().forEach(session->{
//   缓存商品的信息
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {

                String token =UUID.randomUUID().toString().replace("-","");

             if(!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString())){
                 //            缓存商品
                 SeckillSkuRedisTo redisTo=new SeckillSkuRedisTo();

//           1、 sku的基本数据
                 R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                 if(skuInfo.getCode()==0){
                     SkuInfoVo info= skuInfo.getData("skuInfo",new TypeReference<SkuInfoVo>(){});
                     redisTo.setSkuInfoVo(info);
                 }
//            2、sku的秒杀信息
                 BeanUtils.copyProperties(seckillSkuVo,redisTo);

//                3.设置上当前商品的秒杀时间信息
                 redisTo.setStartTime(session.getStartTime().getTime());
                 redisTo.setEndTime(session.getEndTime().getTime());

//                4随机码

                 redisTo.setRandomCode(token);




                 String jsonString=  JSON.toJSONString(redisTo);
                 ops.put(seckillSkuVo.getPromotionSessionId().toString()+"_"+seckillSkuVo.getSkuId().toString(),jsonString);


//                 如果当前这个场次的商品的库存信息已经上架就不需要上架啦



                 //                5.引入分布式信号量   限流
                 RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);


//              商品可以秒杀的数量作为信号量
                 semaphore.trySetPermits(seckillSkuVo.getSeckillCount());

             }



            });


        });


    }
}
